$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'storeFavouredPrice/storefavouredprice/list',
        datatype: "json",
        colModel: [
            {label: 'favouredId', name: 'favouredId', index: 'favoured_id', width: 50, key: true, hidden: true},
            {
                label: '操作', name: 'edit', index: 'edit', width: 30, align: 'center',
                formatter: function (value, options, row) {
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="vm.detail(' + row.favouredId + ');">查看详情</a>');
                    return actions.join(' ');
                }
            },
            {label: '商户id', name: 'sellerId', index: 'seller_id', width: 80, align: 'center'},
            {label: '账套名称', name: 'favouredName', index: 'favoured_name', width: 80, align: 'center'},
            {label: '折扣率', name: 'discountRate', index: 'discount_rate', width: 80, align: 'center'},
            {label: '描述', name: 'describes', index: 'describes', width: 80, align: 'center'},
            {label: '开始时间', name: 'startTime', index: 'start_time', width: 80, align: 'center'},
            {label: '结束时间', name: 'endTime', index: 'end', width: 80, align: 'center'},
            {
                label: '是否禁用', name: 'delFlag', index: 'del_flag', width: 80, align: 'center',
                formatter: function (value, options, row) {

                    if (value == 1) {
                        var actions = [];
                        actions.push('<label class="iSwitch"> <input type="checkbox" onclick="vm.setStart(' + row.favouredId + ',' + value + ');"> <i></i></label>');
                        return actions.join(' ');
                    } else if (value == 0) {
                        var actions = [];
                        actions.push('<label class="iSwitch"> <input type="checkbox"  onclick="vm.setStart(' + row.favouredId + ',' + value + ');" checked> <i></i></label>');
                        return actions.join(' ');
                    }
                }
            },
            {label: '创建人', name: 'createName', index: 'create_name', width: 80, align: 'center'},
            {label: '创建时间', name: 'createTime', index: 'create_time', width: 80, align: 'center'}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
            //请求后台获得门店分类树
            $.get(baseURL + "storeProductPrice/storeproductprice/storeCategoryTree", function (r) {
                vm.storeCategoryTree = r.storeCategoryTree;
            });
        }
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        detailView: false,
        title: null,
        rebate: '', //折扣率
        storeFavouredPrice: {},
        detailData: [],// 一个账套对应的明细信息
        stepPriceData: [],
        stepPriceDataList:[],
        stepPriceDialogVisible: false,
        detailId: null,//当前详情明细对象id
        categoryId: null,
        storeCategoryTree: null,
        storeGoodsProductEntityList: null,
        productId: null,//详情中新增临时变量
        detailObj: {}
    },
    methods: {
        checkBeginDate: function () {
            WdatePicker({
                dateFmt: 'yyyy-MM-dd HH:mm:ss', isShowClear: false, onpicking: function (dp) {
                    vm.storeFavouredPrice.startTime = dp.cal.getNewDateStr();
                }
            })
        },
        checkEndDate: function () {
            WdatePicker({
                dateFmt: 'yyyy-MM-dd HH:mm:ss', isShowClear: false, onpicking: function (dp) {
                    vm.storeFavouredPrice.endTime = dp.cal.getNewDateStr();
                }
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.storeFavouredPrice = {};
            vm.detailData = []
            vm.categoryId=null
            vm.productId=''
        },
        update: function (event) {
            var favouredId = getSelectedRow();
            if (favouredId == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(favouredId)
        },
        saveOrUpdate: function (event) {
            //非空验证
            if (!vm.storeFavouredPrice.favouredName||!vm.storeFavouredPrice.discountRate||!vm.storeFavouredPrice.startTime||!vm.storeFavouredPrice.endTime) {
                alert('必填项不能为空!')
                return
            }
            var url = vm.storeFavouredPrice.favouredId == null ? "storeFavouredPrice/storefavouredprice/save" : "storeFavouredPrice/storefavouredprice/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.storeFavouredPrice),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', (index) =>{
                            if (r.favouredId) {
                                vm.detailData.forEach(value => {
                                    value.favouredId = r.favouredId
                                    //数组转json字符串
                                    value.stepPrice = JSON.stringify(value.stepPrice)
                                    //发送请求保存详情明细
                                    $.ajax({
                                        type: "POST",
                                        url: baseURL + "storeFavouredPrice/storefavouredprice/saveDetail",
                                        contentType: "application/json",
                                        data: JSON.stringify(value),
                                        success: function (r) {
                                            if (r.code == 0) {
                                                //清空临时数据
                                                vm.categoryId=''
                                                vm.productId=''
                                            } else {
                                                alert(r.msg);
                                            }
                                        }
                                    });
                                });
                            }
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var favouredIds = getSelectedRows();
            if (favouredIds == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "storeFavouredPrice/storefavouredprice/delete",
                    contentType: "application/json",
                    data: JSON.stringify(favouredIds),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (favouredId) {
            $.get(baseURL + "storeFavouredPrice/storefavouredprice/info/" + favouredId, function (r) {
                vm.storeFavouredPrice = r.storeFavouredPrice;
            });
        },
        reload: function (event) {
            vm.showList = true;
            vm.detailView=false
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: 1
            }).trigger("reloadGrid");
        },
        //账套详情
        detail(favouredId) {
            vm.showList = false
            vm.detailView = true
            vm.detailObj = {favouredId}
            vm.getInfo(favouredId)
            $.get(baseURL + "storeFavouredPrice/storefavouredprice/detailData/" + favouredId, function (r) {
                vm.detailData = r.detailData;
                if (vm.detailData) {
                    //value.stepPrice得到的是字符串,要转换成数组再使用
                    vm.detailData.forEach(value => value.stepPrice = JSON.parse(value.stepPrice))
                }
            });
        },
        //设置统一折扣
        useRebate() {
            var favouredIds = getSelectedRows();
            if (favouredIds == null) {
                return;
            }
            if (!vm.rebate) {
                alert('折扣率不能为空!')
                return;
            }
            confirm('确定要设置统一折扣？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "storeFavouredPrice/storefavouredprice/useRebate/" + vm.rebate,
                    contentType: "application/json",
                    data: JSON.stringify(favouredIds),
                    success: r => {
                        if (r.code == 0) {
                            alert('操作成功', index => $("#jqGrid").trigger("reloadGrid"));
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        //启用/禁用
        setStart(favouredId, value) {
            let url = "storeFavouredPrice/storefavouredprice/setStart/" + favouredId + "/" + value;
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: {},
                success: r => {
                    if (r.code === 0) {
                        alert('操作成功', index => vm.reload());
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        /*阶梯折扣率设置*/
        openStepPriceDialog: function (row) {
            //先初始化数据
            if (row.stepPrice) {
                vm.stepPriceData = row.stepPrice
            } else {
                vm.stepPriceData = [];
                var temp = {"beginNum": '', "endNum": '', "singlePrice": '', "remark": ''};
                // 加入一条空白数据
                vm.stepPriceData.push(temp);
            }

            // 保留当前option 所在行
            vm.stepPriceRow = row;
            vm.detailId = row.detailId
            vm.stepPriceDialogVisible = true;
        },
        /*保存阶梯价*/
        saveStepPrice: function () {
            var row = vm.stepPriceRow;
            row.stepPrice = vm.stepPriceData;
            //校验起止数量
            var flag=true
            vm.stepPriceData.forEach(value => {
                if (value.beginNum >= value.endNum) {
                    flag=false
                    return false
                }
            })
            if (!flag) {
                alert('结束数量必须大于开始数量')
                return
            }
            if (vm.detailId == null) {
                vm.stepPriceDataList.push(vm.stepPriceData);
            } else {
                //发送请求保存阶梯价
                $.ajax({
                    type: "POST",
                    url: baseURL + "storeFavouredPrice/storefavouredprice/saveStepPrice/" + vm.detailId,
                    contentType: "application/json",
                    data: JSON.stringify(vm.stepPriceData),
                    success: r => {
                        if (r.code === 0) {
                            alert('操作成功');
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
                // 清空临时数据
                vm.stepPriceRow = null;
                vm.stepPriceData = [];
                vm.stepPriceDialogVisible = false

        },

        /*添加一行阶梯价*/
        addOneStepPrice: function () {
            var temp = {"beginNum": '', "endNum": '', "singlePrice": '', "remark": ''};
            vm.stepPriceData.push(temp);
        },

        /*删除一行数据*/
        deleteOneStepPrice: function (index, rows) {
            if (rows.length > 1) {
                rows.splice(index, 1);
            }
        },

        categoryChange: function (value) {
            //取到末级的分类id
            var catId = value[value.length - 1];
            //查找该分类下所有的商品
            $.get(baseURL + "storeProductPrice/storeproductprice/getStoreProductByCatId/" + catId, function (r) {
                vm.storeGoodsProductEntityList = r.storeGoodsProductEntityList;
            });
        },
        //添加商品到明细表
        addDetail() {
            let obj = vm.storeGoodsProductEntityList.find((item) => {
                return item.productId === vm.productId;
            });
            let {productId, productName, storeCategoryId} = obj
            if (vm.storeFavouredPrice.favouredId == null) {
                vm.detailData.push({productId, storeCategoryId, favouredId: null, productName, discountRate: 1})
            } else {
                let {favouredId} = vm.detailObj;
                //组装所需参数  detailObj详情明细对象
                vm.detailObj = {productId, storeCategoryId, favouredId}
                //发送请求
                $.ajax({
                    type: "POST",
                    url: baseURL + "storeFavouredPrice/storefavouredprice/saveDetail",
                    contentType: "application/json",
                    data: JSON.stringify(vm.detailObj),
                    success: r => {
                        if (r.code === 0) {
                            alert('操作成功', () => vm.detail(favouredId));
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
        },
        //通过主键删除详情明细
        deleteRow(detailId) {

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "storeFavouredPrice/storefavouredprice/deleteRow/" + detailId,
                    contentType: "application/json",
                    data: {},
                    success: r => {
                        if (r.code === 0) {
                            alert('操作成功', () => vm.detail(vm.detailObj.favouredId));
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        //保存详情明细的修改
        updateDetail(row) {
            var arr =row.stepPrice
            for (var i = 0; i < arr.length; i++) {
                if (!arr[i].beginNum) {
                    arr.splice(i,1)
                }else {
                    if (arr[i].beginNum>=arr[i].endNum) {
                        arr.splice(i,1)
                    }
                }
            }
            if (arr.length) {
                row.stepPrice = JSON.stringify(arr);
            }else {
                row.stepPrice=''
            }
            //发送请求
            $.ajax({
                type: "POST",
                url: baseURL + "storeFavouredPrice/storefavouredprice/updateDetail/",
                contentType: "application/json",
                data: JSON.stringify(row),
                success: r => {
                    if (r.code === 0) {
                        alert('操作成功', () => vm.detail(row.favouredId));
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },

    }
});